package com.itobase.questionnaire.service.impl;

import com.itobase.questionnaire.model.EnumList.QuestionTypes;
import com.itobase.questionnaire.model.Question;
import com.itobase.questionnaire.model.Questionnaire;
import com.itobase.questionnaire.repository.QuesnaireRepository;
import com.itobase.questionnaire.repository.UserRepository;
import com.itobase.questionnaire.service.IExcelService;
import com.itobase.questionnaire.service.IFileService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.regex.Pattern;

import static com.itobase.questionnaire.util.ExcelUtil.isExcel2007;

/**
 * @author htyu
 * @date 2018/7/30
 */
@Service
public class ExcelService implements IExcelService {


    @Autowired
    QuesnaireService quesnaireService;

    @Autowired
    IFileService fileService;

    @Autowired
    GridFsTemplate gridFsTemplate;

    @Autowired
    QuesnaireRepository quesnaireRepository;

    @Override
    public List<String> upLoad(MultipartFile file) throws IOException {
        //POI处理文件
        InputStream is = file.getInputStream();
        String fileName = file.getOriginalFilename();
        Workbook book;
        Sheet sheet_que, sheet_cho;
        Row row_que, row_cho;
        if (isExcel2007(fileName)) {
            book = new XSSFWorkbook(is);
        } else {
            book = new HSSFWorkbook(is);
        }
        sheet_que = book.getSheetAt(0);
        sheet_cho = book.getSheetAt(1);
        //正则表达式用于匹配字符串
        String pattern_text = ".*text.*";
        String pattern_one = ".*select_one.*";
        String pattern_multiple = ".*select_multiple .*";
        Questionnaire questionnaire = new Questionnaire();
        List<Question> list_que = new LinkedList<>();
        for (int i = 1, j = 0; i < sheet_que.getLastRowNum(); i++) {
            row_que = sheet_que.getRow(i);
            String content = row_que.getCell(0).getStringCellValue();
            if (content.equals("note")) {
                questionnaire.setDescription(row_que.getCell(2).getStringCellValue());
            }
            if (Pattern.matches(pattern_one, content)) {
                j++;
                Question question = new Question();
                question.setOrderNumber(j);
                question.setType(QuestionTypes.Single);
                question.setIssue(row_que.getCell(2).getStringCellValue());
                if (row_que.getCell(6).getStringCellValue().equals("true")) {
                    question.setRequired(true);
                } else {
                    question.setRequired(false);
                }
                List<String> list_cho = new ArrayList<String>();
                for (int m = 1; m <=sheet_cho.getLastRowNum(); m++) {
                    row_cho = sheet_cho.getRow(m);
                    String choice = row_cho.getCell(0).getStringCellValue();
                    if (content.indexOf(choice) != -1) {
                        list_cho.add(row_cho.getCell(2).getStringCellValue());
                    }
                }
                question.setOptions(list_cho);
                list_que.add(question);

            } else if (Pattern.matches(pattern_text, content)) {
                j++;
                Question question = new Question();
                question.setOrderNumber(j);
                question.setType(QuestionTypes.Blanks);
                question.setIssue(row_que.getCell(2).getStringCellValue());
                if (row_que.getCell(6).getStringCellValue().equals("true")) {
                    question.setRequired(true);
                } else {
                    question.setRequired(false);
                }
                list_que.add(question);

            } else if (Pattern.matches(pattern_multiple, content)) {
                j++;
                Question question = new Question();
                question.setOrderNumber(j);
                question.setType(QuestionTypes.Multiple);
                question.setIssue(row_que.getCell(2).getStringCellValue());
                if (row_que.getCell(6).getStringCellValue().equals("true")) {
                    question.setRequired(true);
                } else {
                    question.setRequired(false);
                }
                List<String> list_cho = new ArrayList<String>();
                for (int m = 1; m < sheet_cho.getLastRowNum(); m++) {
                    row_cho = sheet_cho.getRow(m);
                    String choice = row_cho.getCell(0).getStringCellValue();
                    if (content.indexOf(choice) != -1) {
                        list_cho.add(row_cho.getCell(2).getStringCellValue());
                    }
                }

            }
        }

        questionnaire.setXmlStr(excel2xml(file));
        questionnaire.setUsed(false);
        questionnaire.setQuestionList(list_que);

        List<String> value_return = new ArrayList<>();
        Questionnaire questionnaire_new =quesnaireService.insert(questionnaire);
        value_return.add(questionnaire_new.getId());
        value_return.add(questionnaire_new.getXmlStr());
        return value_return;
    }


    /**
     * 将excel转换成xml
     *
     * @param multipartFile
     * @return
     * @throws IOException
     */
    private String excel2xml(MultipartFile multipartFile) throws IOException {
        String fileName = "questionnaire.xls";
        BufferedReader bufferedReader = null;

        String outName = fileName.substring(0, fileName.indexOf(".")).concat(".xml");

        byte[] xlsx = IOUtils.toByteArray(multipartFile.getInputStream());
        File src = new File(fileName);
        File out = new File(outName);
        if (src.exists()) {
            FileUtils.deleteQuietly(src);
        }
        if ((!src.createNewFile()) || (!out.createNewFile())) {
            throw new RuntimeException("空间不足");
        }

        FileUtils.writeByteArrayToFile(src, xlsx);
        String commanderStr = "";
        Properties properties = System.getProperties();
        String os = properties.getProperty("os.name");
        if(os.contains("Linux")){
            commanderStr = "xls2xform ".concat(fileName).concat(" ").concat(outName);
        }else if(os.contains("Windows")){
            commanderStr = "cmd /c xls2xform ".concat(fileName).concat(" ").concat(outName);
        }else{
            throw new RuntimeException("未能识别的操作系统,无法执行Excel转换至xml");
        }

        Process p = Runtime.getRuntime().exec(commanderStr);
        bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = null;
        StringBuilder stringBuilder = new StringBuilder();
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line).append("\n");
        }
        if (stringBuilder.toString().contains("Error")) {
            throw new RuntimeException("Excel格式不标准");
        }
        p.destroy();
        bufferedReader.close();


        InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(out), StandardCharsets.UTF_8);
        bufferedReader = new BufferedReader(inputStreamReader);
        stringBuilder = new StringBuilder();
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line).append("\n");
        }
        bufferedReader.close();
        FileUtils.deleteQuietly(src);
        FileUtils.deleteQuietly(out);

        return stringBuilder.toString();
    }
}
